﻿package com.badibadi.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.location.core.GeoPoint;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.AMap.OnMapClickListener;
import com.amap.api.maps2d.LocationSource.OnLocationChangedListener;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.Tip;
import com.amap.api.services.help.Inputtips.InputtipsListener;
import com.badibadi.infos.Results;
import com.badibadi.maputil.AMapUtil;
import com.badibadi.maputil.ToastUtil;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.EditTextTools;
import com.badibadi.mytools.ImageTools;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.SelectPicLayoutActivity;
import com.badibadi.mytools.TabHostUtils;
import com.badibadi.mytools.Utils;
import com.badibadi.mytools.XUtils;
import com.badibadi.serializable.PostActivityData;
import com.badibadi.slide.music_select;
import com.badibadi.uniclubber.R;
import com.badibadi.uniclubber.R.layout;
import com.badibadi.uniclubber.R.menu;
import com.libjph.util.StringUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

//create_club_number2 StartYearMonthDay endYearMonthDay
public class PostActivity2Activity extends BaseActivity implements
		OnClickListener, LocationSource, AMapLocationListener,
		OnGeocodeSearchListener, TextWatcher, OnMapClickListener,
		OnTouchListener {

	TabHost mTabHost;
	/**
	 * 标记：0线上，1线下
	 */
	private int Flags = 0;
	// 下面是地图的
	private AMap aMap;
	private MapView mapView;
	private OnLocationChangedListener mListener;
	private LocationManagerProxy mAMapLocationManager;
	private GeoPoint geoPoint;
	private boolean isFirstCallBack = true;// 是否为第一次回调

	// 发源地
	private AutoCompleteTextView searchText;
	private ProgressDialog progDialog = null;
	private GeocodeSearch geocoderSearch;
	private Marker geoMarker;
	private Marker regeoMarker;

	// 这里保存要上传的地址名
	private String addressName;
	// 这里保存要上传的经纬度
	private LatLonPoint latLonPoint = new LatLonPoint(40.003662, 116.465271);
	// 上传图片的字段
	private static final int TAKE_PICTURE = 0;
	private static final int CHOOSE_PICTURE = 1;
	private static final int CROP = 2;
	private static final int CROP_PICTURE = 3;
	private static final int SCALE = 5;// 照片缩小比例
	private ImageView iv_image;
	// 下面的是数据
	private String Str_ActivityType;
	private String Str_name;
	private String Str_startTime;
	private String Str_endTime;
	private String Str_Pic;
	private String Str_activityContent;
	private boolean ShowMeTheDongTai;
	private String cid;
	private CheckBox post_activity3_is_dongtai;// 是否显示在动态
	Results results;
	private Button up_slide_music;// 上传音乐
	// 线下的
	private String Str_Adress;
	private String Str_Shihezhuqun;
	private String jingdu;
	private String weidu;

	private String slide_path = null;// 音乐路径

	private String KEY1 = "PostActivity2ActivityOnLine";
	private String KEY2 = "PostActivity2ActivityOffLine";
	private EditText ActiveContent;
	private DisplayImageOptions options;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 2000:
				Utils.ExitPrgress(PostActivity2Activity.this);
				Utils.ExitPrgress_Noclose(PostActivity2Activity.this);
				Utils.ExitProgress_hen(PostActivity2Activity.this);
				Utils.showMessage(PostActivity2Activity.this, getResources()
						.getString(R.string.l_xb18));
				Str_Pic = msg.getData().getString("path");
				ImageLoader.getInstance()
						.displayImage(
								Constants.BadiDownImgUrl + "/"
										+ msg.getData().getString("path")
										+ Constants.Appactivitycover, iv_image,
								options);
//				   ("上传成功返回的地址是:" + Str_Pic);
				break;
			case 1:
				Utils.ExitPrgress(PostActivity2Activity.this);
				Utils.showMessage(PostActivity2Activity.this, getResources()
						.getString(R.string.l_net_error));
				break;
			case 2:
				Utils.ExitPrgress(PostActivity2Activity.this);
				// Utils.showMessage(PostActivity3Activity.this,
				// results.getRetmsg());
				Intent intent = new Intent(PostActivity2Activity.this,
						ActivityReadingActivity.class);
				try {
					intent.putExtra("actId",
							jiexi_and_tiaozhuan(results.getRetmsg()));
					// isOnLine = getIntent().getBooleanExtra("isOnLine",
					// false);
					// intent.putExtra("isOnLine", );

					startActivity(intent);
					PostActivity2Activity.this.finish();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					   
				}
				break;
			case 3:
				Utils.ExitPrgress(PostActivity2Activity.this);
				Utils.showMessage(PostActivity2Activity.this, getResources()
						.getString(R.string.l_xb113));
				break;
			default:
				break;
			}
		}
	};

	private String jiexi_and_tiaozhuan(String d) throws JSONException {
		JSONObject object = new JSONObject(d);
		return object.getString("activityId");
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.post_activity2);
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.noimage)
				.showImageOnFail(R.drawable.noimage).cacheInMemory()
				.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5)).build();
		this.findViewById(R.id.return_btn).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						finish();
					}
				});

		try {
			cid = getIntent().getStringExtra("cid");
		} catch (Exception e) {
			// TODO: handle exception
		}
		// cid = "11";

		settingTabHost();
		mapView = (MapView) findViewById(R.id.map);
		mapView.onCreate(savedInstanceState);// 此方法必须重写
		init();
	}

	private void init() {

		post_activity3_is_dongtai = (CheckBox) this
				.findViewById(R.id.post_activity3_is_dongtai);
		iv_image = (ImageView) this.findViewById(R.id.up_pic);
		iv_image.setOnClickListener(this);
		this.findViewById(R.id.tv_up_pic).setOnClickListener(this);
		this.findViewById(R.id.ActiveContent_linear).setOnClickListener(this);
		// 这一块是日期的
		this.findViewById(R.id.StartYearMonthDay).setOnClickListener(this);
		this.findViewById(R.id.startYearMonthDay).setOnClickListener(this);
		this.findViewById(R.id.EndYearMonthDay).setOnClickListener(this);
		this.findViewById(R.id.endYearMonthDay).setOnClickListener(this);
		// 开始时间的
		this.findViewById(R.id.StartTime).setOnClickListener(this);
		// StartTime
		this.findViewById(R.id.startTime).setOnClickListener(this);
		// 结束时间的
		this.findViewById(R.id.EndTime).setOnClickListener(this);
		// endTime
		this.findViewById(R.id.endTime).setOnClickListener(this);
		this.findViewById(R.id.post_Acitivity2_dingwei)
				.setOnClickListener(this);
		up_slide_music = (Button) this.findViewById(R.id.up_slide_music);
		up_slide_music.setOnClickListener(this);
		searchText = (AutoCompleteTextView) this.findViewById(R.id.fayuandi);
		searchText.addTextChangedListener(this);
		ActiveContent = (EditText) findViewById(R.id.ActiveContent);
		ActiveContent.setOnTouchListener(this);

		progDialog = new ProgressDialog(this);
		geocoderSearch = new GeocodeSearch(this);
		geocoderSearch.setOnGeocodeSearchListener(this);

		if (aMap == null) {
			aMap = mapView.getMap();

			geoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
					.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
			regeoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
					.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
			setUpMap();
		}
	}

	private void setUpMap() {
		// TODO Auto-generated method stub
		aMap.moveCamera(CameraUpdateFactory
				.newLatLngZoom(Constants.CHENGDU, 12));// 设置指定的可视区域地图

		// aMap.setMyLocationStyle(myLocationStyle);
		aMap.setOnMapClickListener(this);// 点击地图上的
		aMap.setLocationSource(this);// 设置定位监听
		aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
		aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
	}

	private void settingTabHost() {
		// TODO Auto-generated method stub
		InitOnlineOrOffline(Flags);
		mTabHost = (TabHost) this.findViewById(R.id.postActivity2_tabhost);
		mTabHost.setup();
		mTabHost.addTab(mTabHost
				.newTabSpec("postActivity2_tabhost one")
				.setIndicator(getResources().getString(R.string.OnlineTheme),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab1));
		mTabHost.addTab(mTabHost
				.newTabSpec("postActivity2_tabhost two")
				.setIndicator(getResources().getString(R.string.Offline),
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(R.id.tab2));
		TabHostUtils.SetTabHost(this, mTabHost);
		mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {

			@Override
			public void onTabChanged(String tabId) {
				// TODO Auto-generated method stub
				switch (mTabHost.getCurrentTab()) {
				case 0:
					InitOnlineOrOffline(0);
					break;
				case 1:
					InitOnlineOrOffline(1);
					break;
				}
			}
		});
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onPause() {
		super.onPause();
		mapView.onPause();
		deactivate();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();
	}

	/**
	 * 初始化线上或者线下
	 * 
	 * @param num
	 *            0,线上,1,线下
	 */
	private void InitOnlineOrOffline(int num) {
		Flags = num;
		if (num == 0) {
			this.findViewById(R.id.ll_0).setVisibility(View.GONE);
			this.findViewById(R.id.Post_activity3_is_dongtai).setVisibility(
					View.VISIBLE);
			Button btn = (Button) this.findViewById(R.id.create_club_number2);
			btn.setText(R.string.Release2);
			// this.findViewById(R.id.post_activity2_checkBox1).setVisibility(
			// View.VISIBLE);
			((TextView) (this.findViewById(R.id.create_club_number2)))
					.setText(getResources().getString(R.string.l_xb186));
			this.findViewById(R.id.create_club_number2).setOnClickListener(
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub

							InitData(true);
							if (Panduan(true)) {
								// PostActivityData postData1 = new
								// PostActivityData(
								// cid, Str_ActivityType, true, Str_name,
								// Str_startTime, Str_endTime, Str_Pic,
								// Str_activityContent);
								// postData1.setLine(true);
								// Intent intent = new Intent(
								// PostActivity2Activity.this,
								// PostActivity3Activity.class);
								// intent.putExtra(KEY2, postData1);
								// startActivity(intent);
								// finish();
								// overridePendingTransition(R.anim.slide_left,
								// R.anim.slide_right);
								post();
							}

						}
					});
		} else if (num == 1) {
			this.findViewById(R.id.ll_0).setVisibility(View.VISIBLE);
			this.findViewById(R.id.Post_activity3_is_dongtai).setVisibility(
					View.GONE);
			((TextView) (this.findViewById(R.id.create_club_number2)))
					.setText("第二步(2/3)");
			Button btn = (Button) this.findViewById(R.id.create_club_number2);
			btn.setText(R.string.Release2);
			// this.findViewById(R.id.post_activity2_checkBox1).setVisibility(
			// View.GONE);
			this.findViewById(R.id.create_club_number2).setOnClickListener(
					new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							InitData(false);
							if (Panduan(false)) {
								PostActivityData postData2 = new PostActivityData(
										cid, Str_ActivityType, false, Str_name,
										Str_startTime, Str_endTime, Str_Adress,
										Str_Shihezhuqun, Str_Pic,
										Str_activityContent, weidu, jingdu);
								postData2.setLine(false);
								Intent intent = new Intent(
										PostActivity2Activity.this,
										PostActivity3Activity.class);
								intent.putExtra(KEY2, postData2);
								if (slide_path != null) {
									intent.putExtra("slide_path", slide_path);
								}
								startActivity(intent);
								finish();
								overridePendingTransition(R.anim.slide_left,
										R.anim.slide_right);
							}

						}
					});
		}
	}

	/**
	 * 用于判断是否没有填和时间是否是符合要求
	 * 
	 * @param isOnline
	 *            是否是线上
	 * @return
	 */
	private boolean Panduan(boolean isOnline) {
		// TODO Auto-generated method stub
		if (isOnline) {
			if (Str_name == null || Str_name == "") {
				ShowToast(PostActivity2Activity.this, ""
						+ getResources().getString(R.string.NameCantNull));
				return false;
			} else if (Str_startTime == null || Str_startTime == "") {
				ShowToast(PostActivity2Activity.this, ""
						+ getResources().getString(R.string.StartTimeNotNull));
				return false;
			} else if (Str_endTime == null || Str_endTime == "") {
				ShowToast(PostActivity2Activity.this, ""
						+ getResources().getString(R.string.EndTimeNotNull));
				return false;
			} else if (Str_Pic == null || Str_Pic == "") {
				ShowToast(
						PostActivity2Activity.this,
						""
								+ getResources().getString(
										R.string.PleaseUpPicActivityFengmian));
				return false;
			} else if (Str_activityContent == null || Str_activityContent == "") {
				ShowToast(
						PostActivity2Activity.this,
						""
								+ getResources().getString(
										R.string.ActivityContentNotNull));
				return false;
			}

		} else if (isOnline == false) {
			if (Str_name == null || Str_name == "") {
				ShowToast(PostActivity2Activity.this, ""
						+ getResources().getString(R.string.NameCantNull));
				return false;
			} else if (Str_startTime == null || Str_startTime == "") {
				ShowToast(PostActivity2Activity.this, ""
						+ getResources().getString(R.string.StartTimeNotNull));
				return false;
			} else if (Str_endTime == null || Str_endTime == "") {
				ShowToast(PostActivity2Activity.this, ""
						+ getResources().getString(R.string.EndTimeNotNull));
				return false;
			} else if (Str_Adress == null || Str_Adress == "") {
				ShowToast(PostActivity2Activity.this, ""
						+ getResources().getString(R.string.AddressNotNull));
				return false;
			} else if (Str_Shihezhuqun == null || Str_Shihezhuqun == "") {
				ShowToast(
						PostActivity2Activity.this,
						""
								+ getResources()
										.getString(
												R.string.PleaseFillInTheSuitableForEthnic));
				return false;
			} else if (Str_Pic == null || Str_Pic == "") {
				ShowToast(
						PostActivity2Activity.this,
						""
								+ getResources().getString(
										R.string.PleaseUpPicActivityFengmian));
				return false;
			} else if (Str_activityContent == null || Str_activityContent == "") {
				ShowToast(
						PostActivity2Activity.this,
						""
								+ getResources().getString(
										R.string.ActivityContentNotNull));
				return false;
			}

		}
		// if(Str_startTime)(Str_endTime)]
		// 下面是用于判断结束时间不能大于开始时间的
		TextView tv_startYearMonthDay = (TextView) this
				.findViewById(R.id.startYearMonthDay);
		TextView tv_endYearMonthDay = (TextView) this
				.findViewById(R.id.endYearMonthDay);
		String tv_1 = tv_startYearMonthDay.getText().toString().trim();
		String tv_2 = tv_endYearMonthDay.getText().toString().trim();
		String[] a1 = tv_1.split("-");
		String[] b1 = tv_2.split("-");

		TextView tv_startTime = (TextView) this.findViewById(R.id.startTime);
		TextView tv_endTime = (TextView) this.findViewById(R.id.endTime);
		String tv_3 = tv_startTime.getText().toString().trim();
		String tv_4 = tv_endTime.getText().toString().trim();
		String[] c1 = tv_3.split(":");
		String[] d1 = tv_4.split(":");
		// 比较年份
		if (Integer.parseInt(a1[0]) < Integer.parseInt(b1[0])) {
			return true;
		} else
		// 比较月份
		if (Integer.parseInt(a1[1]) < Integer.parseInt(b1[1])) {
			return true;
		} else
		// 比较日
		if (Integer.parseInt(a1[2]) < Integer.parseInt(b1[2])) {
			return true;
		} else
		// 比较小时
		if (Integer.parseInt(c1[0]) < Integer.parseInt(d1[0])) {
			return true;
		} else
		// 比较分钟
		if (Integer.parseInt(c1[1]) < Integer.parseInt(d1[1])) {
			return true;
		}
		ShowToast(PostActivity2Activity.this,
				"" + getResources().getString(R.string.EndTimeNotMinStartTime));
		return false;
	}

	/**
	 * 设置资源 (这里将数据保存到类似Str_ActivityType的数组中，然后通过panduan来判断是否没有填写) isOnlion是否为线上
	 */
	// TODO Auto-generated method stub isOnlion
	private void InitData(boolean isOnlion) {

		EditText name = (EditText) findViewById(R.id.p2_Name);
		// 开始时间
		TextView t_startYearMonthDay = (TextView) findViewById(R.id.startYearMonthDay);
		TextView t_startTime = (TextView) findViewById(R.id.startTime);
		// 结束时间
		TextView t_EndYearMonthDay = (TextView) findViewById(R.id.endYearMonthDay);
		TextView t_EndTime = (TextView) findViewById(R.id.endTime);

		// CheckBox checkBox = (CheckBox) this
		// .findViewById(R.id.post_activity2_checkBox1);

		//
		AutoCompleteTextView t_Address = (AutoCompleteTextView) this
				.findViewById(R.id.fayuandi);
		EditText t_shihezhuqun = (EditText) findViewById(R.id.Shihezhuqun);
		EditText t_ActivityContent = (EditText) findViewById(R.id.ActiveContent);
		if (isOnlion) {
			Str_ActivityType = ""
					+ getIntent().getStringExtra("PostActivity1Activity");
			Str_name = "" + name.getText().toString().trim();
			if ("".equals(t_startYearMonthDay.getText().toString().trim())
					|| "".equals(t_startTime.getText().toString().trim())) {
				Str_startTime = "";
			} else
				Str_startTime = ""
						+ t_startYearMonthDay.getText().toString().trim() + " "
						+ t_startTime.getText().toString().trim();

			if ("".equals(t_EndYearMonthDay.getText().toString().trim())
					|| "".equals(t_EndTime.getText().toString().trim())) {
				Str_endTime = "";
			} else
				Str_endTime = ""
						+ t_EndYearMonthDay.getText().toString().trim() + " "
						+ t_EndTime.getText().toString().trim();
			// TUPIANDE URI在uri_0 Str_Pic 在照片的时候就初始化了
			Str_activityContent = ""
					+ ActiveContent.getText().toString().trim();
			// ShowMeTheDongTai = checkBox.isChecked();
		} else if (isOnlion == false) {
			Str_ActivityType = ""
					+ getIntent().getStringExtra("PostActivity1Activity");
			Str_name = "" + name.getText().toString().trim();
			if ("".equals(t_startYearMonthDay.getText().toString().trim())
					|| "".equals(t_startTime.getText().toString().trim())) {
				Str_startTime = "";
			} else
				Str_startTime = ""
						+ t_startYearMonthDay.getText().toString().trim() + " "
						+ t_startTime.getText().toString().trim();

			if ("".equals(t_EndYearMonthDay.getText().toString().trim())
					|| "".equals(t_EndTime.getText().toString().trim())) {
				Str_endTime = "";
			} else
				Str_endTime = ""
						+ t_EndYearMonthDay.getText().toString().trim() + " "
						+ t_EndTime.getText().toString().trim();
			Str_Adress = "" + t_Address.getText().toString().trim();
			Str_Shihezhuqun = "" + t_shihezhuqun.getText().toString().trim();
			// Str_Pic
			Str_activityContent = t_ActivityContent.getText().toString().trim();

		}

	}

	// @Override
	// public boolean onCreateOptionsMenu(Menu menu) {
	// getMenuInflater().inflate(R.menu.post_activity, menu);
	// return true;
	// }

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	// 点击地图的上东西后回调
	@Override
	public void onMapClick(LatLng latlng) {
		// TODO Auto-generated method stub
		if (aMap != null && latlng != null) {
			aMap.clear();
			// MarkerOptions markerOptions=new MarkerOptions();
			// markerOptions.

			geoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
					.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
			// aMap.addMarker(new MarkerOptions());
			geoMarker.setPosition(latlng);
			getAddress(AMapUtil.convertToLatLonPoint(latlng));
			aMap.invalidate();
			latLonPoint = AMapUtil.convertToLatLonPoint(latlng);
//			   
//					"address+====>" + addressName + " latLonPoint--->"
//							+ latLonPoint.getLatitude() + ","
//							+ latLonPoint.getLongitude());
			jingdu = "" + latLonPoint.getLongitude();
			weidu = "" + latLonPoint.getLatitude();

		}
	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub

	}

	// TextWatcher

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		String newText = s.toString().trim();
		Inputtips inputTips = new Inputtips(PostActivity2Activity.this,
				new InputtipsListener() {

					@Override
					public void onGetInputtips(List<Tip> tipList, int rCode) {
						if (rCode == 0) {// 正确返回
							List<String> listString = new ArrayList<String>();
							for (int i = 0; i < tipList.size(); i++) {
								listString.add(tipList.get(i).getName());
							}
							ArrayAdapter<String> aAdapter = new ArrayAdapter<String>(
									getApplicationContext(),
									R.layout.route_inputs, listString);
							searchText.setAdapter(aAdapter);
							aAdapter.notifyDataSetChanged();
						}
					}
				});
		try {
			inputTips.requestInputtips(newText, null);// 第一个参数表示提示关键字，第二个参数默认代表全国，也可以为城市区号

		} catch (AMapException e) {
			   
		}
	}

	/**
	 * 地理编码查询回调
	 */
	@Override
	public void onGeocodeSearched(GeocodeResult result, int rCode) {
		// // TODO Auto-generated method stub
		dismissDialog();
		if (rCode == 0) {
			if (result != null && result.getGeocodeAddressList() != null
					&& result.getGeocodeAddressList().size() > 0) {
				GeocodeAddress address = result.getGeocodeAddressList().get(0);
				aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
						AMapUtil.convertToLatLng(address.getLatLonPoint()), 15));
				geoMarker.setPosition(AMapUtil.convertToLatLng(address
						.getLatLonPoint()));
				addressName = "经纬度值:" + address.getLatLonPoint() + "\n位置描述:"
						+ address.getFormatAddress();
				// 这里保存要上传的经纬度
				latLonPoint = address.getLatLonPoint();
				jingdu = "" + latLonPoint.getLongitude();
				weidu = "" + latLonPoint.getLatitude();
//				   
//						+ "///" + latLonPoint.getLongitude());

				ShowToast(PostActivity2Activity.this, addressName);
			} else {
				ToastUtil.show(PostActivity2Activity.this, R.string.no_result);
			}

		} else if (rCode == 27) {
			ToastUtil.show(PostActivity2Activity.this, R.string.error_network);
		} else if (rCode == 32) {
			ToastUtil.show(PostActivity2Activity.this, R.string.error_key);
		} else {
			ToastUtil.show(PostActivity2Activity.this,
					getString(R.string.error_other) + rCode);
		}
	}

	// /**
	// * 逆地理编码回调
	// */
	@Override
	public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
		// // TODO Auto-generated method stub
		dismissDialog();
		if (rCode == 0) {
			if (result != null && result.getRegeocodeAddress() != null
					&& result.getRegeocodeAddress().getFormatAddress() != null) {
				addressName = result.getRegeocodeAddress().getFormatAddress();
				jingdu = ""
						+ result.getRegeocodeQuery().getPoint().getLongitude();
				weidu = ""
						+ result.getRegeocodeQuery().getPoint().getLatitude();
				if (addressName != ""
						&& searchText.getText().toString().trim() != "") {
					searchText.setText(""
							+ result.getRegeocodeAddress().getFormatAddress());
				}
				// aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
				// AMapUtil.convertToLatLng(latLonPoint), 15));
				regeoMarker.setPosition(AMapUtil.convertToLatLng(latLonPoint));
				ToastUtil.show(PostActivity2Activity.this, addressName);
			} else {
				ToastUtil.show(PostActivity2Activity.this, R.string.no_result);
			}
		} else if (rCode == 27) {
			ToastUtil.show(PostActivity2Activity.this, R.string.error_network);
		} else if (rCode == 32) {
			ToastUtil.show(PostActivity2Activity.this, R.string.error_key);
		} else {
			ToastUtil.show(PostActivity2Activity.this,
					getString(R.string.error_other) + rCode);
		}
	}

	/**
	 * 隐藏进度条对话框
	 */
	public void dismissDialog() {
		if (progDialog != null) {
			progDialog.dismiss();
		}
	}

	/**
	 * 定位成功后回调函数
	 */
	@Override
	public void onLocationChanged(AMapLocation aLocation) {
		//    
		if (mListener != null && aLocation != null) {

			//    
			// "aLocation.getLatitude()--->"+aLocation.getLatitude()+"  aLocation.getLongitude()===>"+aLocation.getLongitude());
			mListener.onLocationChanged(aLocation);// 显示系统小蓝点

			// geoPoint=new GeoPoint((int) (aLocation.getLatitude() * 1E6),
			// (int) (aLocation.getLongitude() * 1E6));
			// //用给定的经纬度构造一个GeoPoint，单位是微度 (度 * 1E6)
			// CameraUpdateFactory a=CameraUpdateFactory.newLatLngZoom(new
			// LatLng(arg0, arg1), arg1)

			if (isFirstCallBack == true) {
				aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
						aLocation.getLatitude(), aLocation.getLongitude()), 12));// 设置指定的可视区域地图
				isFirstCallBack = false;
				latLonPoint = new LatLonPoint(aLocation.getLatitude(),
						aLocation.getLongitude());
				getAddress(new LatLonPoint(aLocation.getLatitude(),
						aLocation.getLongitude()));
			}
		}
	}

	/**
	 * 激活定位
	 */
	@Override
	public void activate(OnLocationChangedListener listener) {
		mListener = listener;
		if (mAMapLocationManager == null) {
			mAMapLocationManager = LocationManagerProxy.getInstance(this);
			/*
			 * mAMapLocManager.setGpsEnable(false);
			 * 1.0.2版本新增方法，设置true表示混合定位中包含gps定位，false表示纯网络定位，默认是true Location
			 * API定位采用GPS和网络混合定位方式
			 * ，第一个参数是定位provider，第二个参数时间最短是2000毫秒，第三个参数距离间隔单位是米，第四个参数是定位监听者
			 */
			mAMapLocationManager.requestLocationUpdates(
					LocationProviderProxy.AMapNetwork, 2000, 10, this);
		}
	}

	/**
	 * 停止定位
	 */
	@Override
	public void deactivate() {
		mListener = null;
		if (mAMapLocationManager != null) {
			mAMapLocationManager.removeUpdates(this);
			mAMapLocationManager.destory();
		}
		mAMapLocationManager = null;
	}

	/**
	 * 显示进度条对话框
	 */
	public void showDialog() {
		progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progDialog.setIndeterminate(false);
		progDialog.setCancelable(true);
		progDialog.setMessage(getResources().getString(R.string.l_xb63));
		progDialog.show();
	}

	/**
	 * 响应逆地理编码
	 */
	public void getAddress(final LatLonPoint latLonPoint) {
		showDialog();
		RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200,
				GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
		geocoderSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
	}

	/**
	 * 响应地理编码
	 */
	public void getLatlon(final String name) {
		showDialog();
		GeocodeQuery query = new GeocodeQuery(name, null);// 第一个参数表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode，
		geocoderSearch.getFromLocationNameAsyn(query);// 设置同步地理编码请求
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent;
		switch (v.getId()) {
		case R.id.post_Acitivity2_dingwei:
			// getAddress();
			getLatlon("" + searchText.getText().toString().trim());
			break;
		// 设置开始年月日Diaglog
		case R.id.StartYearMonthDay:
			TextView t = (TextView) findViewById(R.id.startYearMonthDay);
			com.badibadi.mytools.Dialog.createDateDialog_1(
					PostActivity2Activity.this, t);
			break;

		case R.id.startYearMonthDay:
			TextView tstart = (TextView) findViewById(R.id.startYearMonthDay);
			com.badibadi.mytools.Dialog.createDateDialog_1(
					PostActivity2Activity.this, tstart);
			break;
		// 设置结束年月日Diaglog
		case R.id.EndYearMonthDay:
			TextView t1 = (TextView) findViewById(R.id.endYearMonthDay);
			com.badibadi.mytools.Dialog.createDateDialog_1(
					PostActivity2Activity.this, t1);
			break;
		case R.id.endYearMonthDay:
			TextView t11 = (TextView) findViewById(R.id.endYearMonthDay);
			com.badibadi.mytools.Dialog.createDateDialog_1(
					PostActivity2Activity.this, t11);
			break;
		// 设置开始时间Diaglog
		case R.id.StartTime:
			TextView t2 = (TextView) findViewById(R.id.startTime);
			com.badibadi.mytools.Dialog.createTimeDialog(
					PostActivity2Activity.this, t2);
			break;
		case R.id.startTime:
			TextView t21 = (TextView) findViewById(R.id.startTime);
			com.badibadi.mytools.Dialog.createTimeDialog(
					PostActivity2Activity.this, t21);
			break;
		// 设置结束时间Diaglog
		case R.id.EndTime:
			TextView t3 = (TextView) findViewById(R.id.endTime);
			com.badibadi.mytools.Dialog.createTimeDialog(
					PostActivity2Activity.this, t3);
			break;
		// 设置结束时间Diaglog
		case R.id.endTime:
			TextView t31 = (TextView) findViewById(R.id.endTime);
			com.badibadi.mytools.Dialog.createTimeDialog(
					PostActivity2Activity.this, t31);
			break;
		case R.id.up_pic:
			// 截图后显示
			// showPicturePicker(PostActivity2Activity.this, true);
			intent = new Intent(PostActivity2Activity.this,
					SelectPicLayoutActivity.class);
			intent.putExtra("Cutting", "yes");// 传入是否需要裁剪的参数，传则不需要，不传则需要
			startActivityForResult(intent, 0);
			break;
		case R.id.tv_up_pic:
			// 截图后显示
			// showPicturePicker(PostActivity2Activity.this, true);
			intent = new Intent(PostActivity2Activity.this,
					SelectPicLayoutActivity.class);
			intent.putExtra("Cutting", "yes");// 传入是否需要裁剪的参数，传则不需要，不传则需要
			startActivityForResult(intent, 0);
			break;
		case R.id.up_slide_music:
			intent = new Intent(PostActivity2Activity.this, music_select.class);
			startActivityForResult(intent, 5);
			break;
		case R.id.ActiveContent_linear:
			ActiveContent.setFocusable(true);
			ActiveContent.setFocusableInTouchMode(true);
			ActiveContent.requestFocus();
			EditTextTools.CloseOrConsultingEvaluation(ActiveContent);
			break;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 5 && resultCode == 300) {
			String path = data.getStringExtra("slide_path");
//			   
			if (Utils.panduan_is_cunzai(path, "/Public/music/")) {
				slide_path = path;
				Utils.showMessage(PostActivity2Activity.this, getResources()
						.getString(R.string.wx_txt_103));
			} else {
				Utils.showMessage(PostActivity2Activity.this, getResources()
						.getString(R.string.wx_txt_102));
			}
		}

		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			// 拍照
			case TAKE_PICTURE:
				// 将保存在本地的图片取出并缩小后显示在界面上
				// Bitmap bitmap = BitmapFactory.decodeFile(Environment
				// .getExternalStorageDirectory() + "/image.jpg");
				// Bitmap newBitmap = ImageTools.zoomBitmap(bitmap,
				// bitmap.getWidth() / SCALE, bitmap.getHeight() / SCALE);
				// // 由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
				// bitmap.recycle();
				//
				// // 将处理过的图片显示在界面上，并保存到本地
				//
				// iv_image.setImageBitmap(newBitmap);
				//
				// ImageTools.savePhotoToSDCard(newBitmap, Environment
				// .getExternalStorageDirectory().getAbsolutePath(),
				// String.valueOf(System.currentTimeMillis()));
				//    
				// + Environment.getExternalStorageDirectory()
				// .getAbsolutePath());
				if (resultCode == Activity.RESULT_OK) {
					if (data != null) {
						if (!StringUtil
								.isNullOrEmpty(data
										.getStringExtra(SelectPicLayoutActivity.KEY_PHOTO_PATH))) {
							String picPath = data
									.getStringExtra(SelectPicLayoutActivity.KEY_PHOTO_PATH);
							//    ("图片地址是:" + picPath);

							Bitmap bitmap = BitmapFactory.decodeFile(picPath);
							Bitmap newBitmap = ImageTools.zoomBitmap(bitmap,
									bitmap.getWidth() / SCALE,
									bitmap.getHeight() / SCALE);
							// 由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
							bitmap.recycle();
							// 将处理过的图片显示在界面上，并保存到本地
							// iv_image.setImageBitmap(newBitmap);
							// userDataSet.UserDataSet2(userInfoModel, 2,
							// picPath,
							// true);
							XUtils.UpImg(picPath, PostActivity2Activity.this,
									handler);
						}
					}

				}
				break;
			// 选择照片
			case CHOOSE_PICTURE:
				if (data != null) {
					ContentResolver resolver = getContentResolver();
					// 照片的原始资源地址
					Uri originalUri = data.getData();
					try {
						// 使用ContentProvider通过URI获取原始图片
						Bitmap photo = MediaStore.Images.Media.getBitmap(
								resolver, originalUri);
						if (photo != null) {
							// 为防止原始图片过大导致内存溢出，这里先缩小原图显示，然后释放原始Bitmap占用的内存
							Bitmap smallBitmap = ImageTools.zoomBitmap(photo,
									photo.getWidth() / SCALE, photo.getHeight()
											/ SCALE);
							// 释放原始图片占用的内存，防止out of memory异常发生
							photo.recycle();

							iv_image.setImageBitmap(smallBitmap);

						}
					} catch (FileNotFoundException e) {
						   
					} catch (IOException e) {
						   
					}
				}

				break;

			case CROP:

				Uri uri = null;
				if (data != null) {
					uri = data.getData();
//					   ("Data");
				} else {
//					   ("File");
					String fileName = getSharedPreferences("temp",
							Context.MODE_WORLD_WRITEABLE).getString("tempName",
							"");
					uri = Uri.fromFile(new File(Environment
							.getExternalStorageDirectory(), fileName));
//					   
//							"路径：_+" + Environment.getExternalStorageDirectory()
//									+ fileName);
				}
				cropImage(uri, 500, 500, CROP_PICTURE);
				break;

			case CROP_PICTURE:
				Bitmap photo = null;
				Uri photoUri = data.getData();

				if (photoUri != null) {
					photo = BitmapFactory.decodeFile(photoUri.getPath());
				}
				if (photo == null) {
					Bundle extra = data.getExtras();
					if (extra != null) {
						photo = (Bitmap) extra.get("data");
						ByteArrayOutputStream stream = new ByteArrayOutputStream();
						photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
					}
				}

				iv_image.setImageBitmap(photo);
				String uri0 = UpPicSavePath;
				String na = String.valueOf(System.currentTimeMillis());
				// Str_Pic = uri0 + "/" + na;
				break;
			default:
				break;
			}
		}
	}

	// 截取图片
	public void cropImage(Uri uri, int outputX, int outputY, int requestCode) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", outputX);
		intent.putExtra("outputY", outputY);
		intent.putExtra("outputFormat", "JPEG");
		intent.putExtra("noFaceDetection", true);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, requestCode);
	}

	/** 发活动 */

	private void post() {
		Utils.showPrgress(PostActivity2Activity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				Map<String, Object> params = new HashMap<String, Object>();
				try {
					params.put("activity", fengzhuang());
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					   
				}
				String content = Utils.sendRequest(params, Constants.BadiUrl_1
						+ "activity/post");
//				   ("俱乐部创建活动提交的数据是:" + params.toString());
				if (content != null) {
//					   ("俱乐部创建活动返回的数据是:" + content);
					results = Utils.checkResult_NNN(getApplicationContext(),
							content);
					if (results != null && !results.getRetmsg().equals("null")
							&& results.isRet()) {
						//    ("俱乐部创建活动返回的数据是:"
						// + results.getRetmsg());
						handler.sendEmptyMessage(2);
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	// 一定是线上的
	// PostActivityData postData1 = new PostActivityData(
	// cid, Str_ActivityType, true, Str_name,
	// Str_startTime, Str_endTime, Str_Pic,
	// Str_activityContent);
	private JSONObject fengzhuang() throws JSONException {
		JSONObject object = new JSONObject();
		object.put("cid", cid);// （线上AND线下）俱乐部ID
		object.put("uid", Utils.getUid(PostActivity2Activity.this));// （线上AND线下）发布活动的用户ID
		object.put("typeid", Str_ActivityType);// （线上AND线下）活动类别
		object.put("activity_name", Str_name);// 线上AND线下）活动名称
		object.put("start_time", Str_startTime);// （线上AND线下）活动开始时间（格式为：2014-09-22
		// 09:30）
		object.put("end_time", Str_endTime);// （线上AND线下）活动结束时间（格式为：2014-09-22
		// 09:30）注意，结束时间一定大于开始时间
		object.put("activity_editor", Str_activityContent);// （线上AND线下）（格式为：2014-09-22
		// 09:30）活动内容简介
		object.put("activity_image", Str_Pic);// （线上AND线下）活动封面图
		// 格式：/Public/Uploads/2014-06/140263893872417.jpg
		// if (jinbinum != null || !jinbinum.equals("0")) {
		// object.put("is_gold", "1");// （线上AND线下）加入该活动是否需要金币 0：否，1：是
		// object.put("activity_gold", jinbinum);// （线上AND线下）若需要金币，那么需要多少金币
		// // 当不需要金币加入时，则为0
		// } else {
		object.put("is_gold", "0");
		object.put("activity_gold", "0");
		// }
		// if (personnum != null || !personnum.equals("0")) {
		// object.put("is_limit", "1");// （线上AND线下）该活动是否限制人数加入 0：否，1：是
		// object.put("activity_limit", personnum);//
		// （线上AND线下）若限制人数加入，那么人数上限，当不限制时则为0
		// } else {
		object.put("is_limit", "0");
		object.put("activity_limit", "0");
		// }

		object.put("activity_status", "1");// （线上AND线下）加入该活动的权限
		// 1：所有人，2：会员
		// if (postActivityData.isLine()) {
		object.put("is_online", "1");// （线上AND线下）线上OR线下 0：线下，1：线上

		if (slide_path != null) {
			object.put("music", slide_path);
		}
		// } else {
		// object.put("is_online", "0");
		// // }
		// object.put("activity_organization", "" + name);// （线下）发起组织
		// object.put("activity_organization_introduce", "" + contents);//
		// （线下）发起组织介绍
		// object.put("activity_class", "" +
		// postActivityData.getShihezhuqun());// （线下）适合族群
		// object.put("activity_address", "" + postActivityData.getAdress());//
		// （线下）活动地点
		// object.put("map_x", "" + postActivityData.getMap_x());// （线下）活动地点纬度
		// // 格式：40.345367
		// // 0.0000000
		// object.put("map_y", "" + postActivityData.getMap_y());// （线下）活动地点经度
		// // 格式：130.569536
		// // 0.0000000
		if (post_activity3_is_dongtai.isChecked() == true) {
			object.put("is_show", "1");// （线上AND线下）是否显示到动态栏 0：否，1：是
		} else {
			object.put("is_show", "0");// （线上AND线下）是否显示到动态栏 0：否，1：是
		}

		return object;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.ActiveContent:
			// case R.id.ActiveContent_linear:
			v.getParent().requestDisallowInterceptTouchEvent(true);
//			   
			switch (event.getAction() & MotionEvent.ACTION_MASK) {
			case MotionEvent.ACTION_UP:
				v.getParent().requestDisallowInterceptTouchEvent(false);
				break;
			}
			break;

		default:
			break;
		}
		return false;
	}

}
